package cn.dida.core;

import cn.dida.model.Sysres;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 系统资源信息
 *
 * @author weiwei1
 */
public class SysresMap {

    private static PathMatcher pathMatcher = new AntPathMatcher();

    // 导航节点
    public static ArrayList<Sysres> resNodes = new ArrayList<>();
    public static ArrayList<Sysres> resTree = new ArrayList<>();

    // 初始化
    public static void init(ArrayList<Sysres> resTree, ArrayList<Sysres> resNodes) {
        SysresMap.resNodes = resNodes;
        SysresMap.resTree = resTree;
    }

    //获取当前路径所属的节点
    public static Sysres getNavNodeByPath(String path, String method) {
        for (Sysres resNode : resNodes) {
            if (pathMatcher.match(resNode.getPath(), path) && StringUtils.equals(resNode.getMethod(), method)) {
                return resNode;
            }
        }
        return null;
    }

    //获取当前路径的节点链集合
    public static List<Sysres> getNavNodeLinkByPath(String path, String method) {
        List<Sysres> resNodeLink = new ArrayList<>();
        Sysres leafNode = getNavNodeByPath(path, method);
        if (leafNode == null) {
            return resNodeLink;
        }
        appendParent(resNodeLink, leafNode);
        // 按根节点到末节点的顺序排序
        Collections.reverse(resNodeLink);
        return resNodeLink;
    }

    private static void appendParent(List<Sysres> resNodeLink, Sysres leafNode) {
        resNodeLink.add(leafNode);
        if (leafNode.getParent() != null) {
            appendParent(resNodeLink, leafNode.getParent());
        }
    }

    // 将零散的节点拼装成树形结构
    public static <T extends Sysres> List<T> makeTree(List<T> nodes) {
        List<T> resTree = new ArrayList<>();
        for (Sysres res1 : nodes) {
            if (res1.getParentId() == null) {
                resTree.add((T) res1);
            } else {
                for (Sysres res2 : nodes) {
                    if (res1.getParentId().intValue() == res2.getId().intValue()) {
                        res1.setParent(res2);
                        res2.getChildren().add(res1);
                        break;
                    }
                }
            }
        }
        return resTree;
    }


    // 排序
    public static <T extends Sysres> void sort(List<T> nodes) {
        nodes.sort((o1, o2) -> {
            if (o1.getNo() != null || o2.getNo() != null) {
                if (o1.getNo() != null && o2.getNo() != null) {
                    return o1.getNo().compareTo(o2.getNo());
                } else {
                    return o1.getNo() == null ? 1 : -1;
                }
            }
            return 0;
        });
    }
}
